package com.boot.dog.rest.core;

import cn.hutool.core.collection.CollUtil;
import com.boot.dog.common.auth.DogUser;
import com.boot.dog.common.annotation.SysLog;
import com.boot.dog.common.constant.SecurityConst;
import com.boot.dog.common.util.ApiResult;
import com.boot.dog.common.util.Result;
import com.boot.dog.common.util.SecurityUtil;
import com.boot.dog.entities.dto.PermissionDto;
import com.boot.dog.entities.pojo.Permission;
import com.boot.dog.entities.pojo.User;
import com.boot.dog.service.PermissionService;
import com.boot.dog.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: MaxLv
 * @Date: 2020/1/12
 */
@RestController
@RequestMapping("/core/permission")
@AllArgsConstructor
public class PermissionRest {

    private final PermissionService permissionService;

    private final UserService userService;

    @PostMapping("/savePermission")
    @SysLog(desc = "添加权限")
    @ApiOperation(value = "添加权限")
    public ApiResult<Void> savePermission(@RequestBody PermissionDto dto) {
        Permission permission = new Permission();
        BeanUtils.copyProperties(dto, permission);
        return permissionService.savePermission(permission);
    }

    @GetMapping("/searchPermissions")
    @ApiOperation(value = "检索权限")
    public ApiResult<List<Permission>> searchPermissions(String title) {
        return permissionService.searchPermissions(title);
    }

    @DeleteMapping("/delById/{id}")
    @SysLog(desc = "删除权限")
    @ApiOperation(value = "删除权限")
    public ApiResult<Void> delById(@PathVariable Integer id) {
        return permissionService.delById(id);
    }

    @PutMapping("/editPermission")
    @SysLog(desc = "编辑权限")
    @ApiOperation(value = "编辑权限")
    public ApiResult<Void> editPermission(@RequestBody PermissionDto dto) {
        Permission permission = new Permission();
        BeanUtils.copyProperties(dto, permission);
        return permissionService.editPermission(permission);
    }

    @GetMapping("/getUserMenuList")
    @ApiOperation(value = "获取用户菜单权限")
    public ApiResult<List<Permission>> getUserMenuList() {
        DogUser authUser = SecurityUtil.getUser();
        User user = userService.findByUsername(authUser.getUsername());

        List<Permission> menuList = user.getPermissions().stream().filter(p -> SecurityConst.PERMISSION_PAGE.equals(p.getType()) && SecurityConst.LEVEL_ONE.equals(p.getLevel())).collect(Collectors.toList());
        List<Permission> secondMenuList = user.getPermissions().stream().filter(p -> SecurityConst.PERMISSION_PAGE.equals(p.getType()) && SecurityConst.LEVEL_TWO.equals(p.getLevel())).collect(Collectors.toList());
        List<Permission> buttonPermissions = user.getPermissions().stream().filter(p -> SecurityConst.PERMISSION_OPERATION.equals(p.getType())
                && SecurityConst.LEVEL_THREE.equals(p.getLevel())).collect(Collectors.toList());
        
        secondMenuList.forEach(p -> p.setPermTypes(buttonPermissions.stream().filter(pe -> p.getId().equals(pe.getParentId())).map(Permission::getButtonType).collect(Collectors.toList())));
        menuList.forEach(p -> p.setChildren(secondMenuList.stream().filter(pe -> p.getId().equals(pe.getParentId())).collect(Collectors.toList())));
        return Result.of(menuList);
    }

    @GetMapping("/getPermissions")
    @ApiOperation(value = "获取权限列表")
    public ApiResult<List<Permission>> getPermissions() {
        List<Permission> list = permissionService.findByLevelOrderBySortOrder(SecurityConst.LEVEL_ONE);
        if (CollUtil.isEmpty(list)) {
            return Result.of(list);
        }
        list.forEach(p_1 -> {
            List<Permission> children_1 = permissionService.findByParentIdOrderBySortOrder(p_1.getId());
            p_1.setChildren(children_1);
            if (CollUtil.isNotEmpty(children_1)) {
                children_1.forEach(p_2 -> {
                    List<Permission> children_2 = permissionService.findByParentIdOrderBySortOrder(p_2.getId());
                    p_2.setChildren(children_2);
                });
            }
        });
        return Result.of(list);
    }

    @GetMapping("/getCurrPermissions")
    @ApiOperation(value = "获取当前用户权限列表")
    public ApiResult<List<Permission>> getCurrPermissions() {
        DogUser authUser = SecurityUtil.getUser();
        User user = userService.findUserByUsername(authUser.getUsername());
        List<Permission> list = permissionService.findCurrByLevelOrderBySortOrder(SecurityConst.LEVEL_ONE, user);
        if (CollUtil.isEmpty(list)) {
            return Result.of(list);
        }
        list.forEach(p_1 -> {
            List<Permission> children_1 = permissionService.findCurrByParentIdOrderBySortOrder(p_1.getId(), user);
            p_1.setChildren(children_1);
            if (CollUtil.isNotEmpty(children_1)) {
                children_1.forEach(p_2 -> {
                    List<Permission> children_2 = permissionService.findCurrByParentIdOrderBySortOrder(p_2.getId(), user);
                    p_2.setChildren(children_2);
                });
            }
        });
        return Result.of(list);
    }
}
